import axios from "axios";
import Cookie from "js-cookie";
import router from "../router";
import SELF from "../main";
import { logout as logoutFn} from '@/api'
import StorageModel from "@/utils/storage";
import { AUTH, X_TOKEN, XTOKEN } from "@/utils/constant";
import { Toast } from 'vant';
import md5 from "js-md5";
import {decrypt} from "@/utils";
const Storage = new StorageModel();

export const logout = () => {
  logoutFn();
  router.push({ name: "login" });
  location.reload();
};
const alertDialog = text => {
  Toast({
    className: 'toastClass',
    message: text,
    icon: 'cross',
  });
  // SELF.$swal.warning(text)
};
const baseUrl = process.env.VUE_APP_BASEURL;
var lockAlert = false
axios.defaults.timeout = 30 * 1000;
axios.defaults.withCredentials = true;

axios.interceptors.request.use(
  config => {
    // 这里的config包含每次请求的内容
    let token = Storage.get(AUTH);
    let xtoken = Storage.get(XTOKEN);
    if (token) {
      axios.defaults.headers["xtoken"] = xtoken;
      axios.defaults.headers["Authorization"] = "Bearer " + token;
    } else {
      let { name, query } = router.currentRoute;
      if (name === "login") {
        router.push({ name: "login", query });
      }
    }
    return config;
  },
  err => {
    console.log(err);
    return Promise.reject(err);
  }
);
axios.interceptors.response.use(
  res => {
    try {
      if (res.data.code === 1) {
        let { name, query } = router.currentRoute;
        let msg = "";
        let msgIndex = res.data.message.indexOf("错误状态码");
        let wzerror = res.data.message.indexOf("未知错误");
        let nouserinfo = res.data.message.indexOf("用户信息不存在");
        let nouser = res.data.message.indexOf("账号未登录");
        let notoken = res.data.message.indexOf("token解析失败");
        let tokenExpired = res.data.message.indexOf("token已过期");
        let noLogin = res.data.message.indexOf("未登录");
        let username = res.data.message.indexOf("请输入用户名");
        let usernamedis = res.data.message.indexOf("用户名已存在");
        let matchError = res.data.message.indexOf("买入单快速匹配失败")

        if(matchError !== -1){
          return res;
        }

        if (msgIndex !== -1) {
          msg = res.data.message.substring(0, msgIndex);
        } else {
          msg = res.data.message;
        }
        if (tokenExpired != -1 || noLogin != -1 || notoken != -1 || nouser !== -1) {
          alertDialog("用户已登出，请重新登录!");
          setTimeout(() => {
            logout();
          }, 1000);
          return res;
        }
        if (username !== -1 || usernamedis !== -1) {
          SELF.$notify.clear();
          return res;
        }
        if (name != "login" && name != "home" && name != "dw" && name !='bindHasAccount') {
          if (nouserinfo !== -1) {
            alertDialog('账号状态失效，请重新登录');
            setTimeout(() => {
              logout();
            }, 1000);
            return res;
          }
        }
        if (!lockAlert) {
          if (wzerror !== -1) {
            console.log(res.data.message)
            let method = res.config.method
            if (method == 'post') {
              alertDialog("未知错误！");
            } else {
              alertDialog("努力加载中！");
            }
            return res;
          }
          lockAlert = true;
          setTimeout(() => {
            lockAlert = false;
          }, 2000);
        }

        if(msg){
          alertDialog(msg);
        }
      }
    } catch (error) {
      console.log(error)
      let method = res.config.method
      if (method == 'post') {
        alertDialog("未知错误！");
      } else {
        alertDialog("努力加载中！");
      }
    }
    return res;
  },
  error => {
    if (axios.isCancel(error)) {
      return new Promise(() => {});
    }
    else {
      if (error.response) {
        switch (error.response.status) {
          case 401:
          case 403:
            SELF.$notify.clear();
            alertDialog("登录失效！");
            delete axios.defaults.headers["Authorization"];
            this.$logout()
            return Promise.reject(error.response);
          case 503:
          case 502:
            alertDialog("服务器出错");
            return Promise.reject(error.response);
          case 500:
            // SELF.$router.push('/servernot');
            alertDialog("请查看网络是否断开");
            return Promise.reject(error.response);
        }
      }
      return Promise.reject(error.response); // 返回接口返回的错误信息
    }
  }
);
let t = null;

function setX_Token() {
  setX_ToKen();
  t = setTimeout(() => {
    clearTimeout(t);
    setX_Token();
  }, 60 * 1000);
}

async function setX_ToKen() {
  await axios.get(baseUrl + "/member/t?_=" + new Date().getTime(),{
    headers: {}
  }).then(res => {
    Storage.set(X_TOKEN, res.data.data);
  });
}

export default {
  get(url, params = {}, config = {}) {
    let token = Storage.get(AUTH);
    let xtoken = Storage.get(XTOKEN);
    this.setToken(token);
    this.setXToKen(xtoken);
    let headers = config.headers?config.headers:{}
    return axios.get(baseUrl + url, {
      params,
      ...config,
      headers: {
        ...headers
      }
    });
  },
  post(url, params = {}, config = {}) {
    let token = Storage.get(AUTH);
    let xtoken = Storage.get(XTOKEN);
    let arr = ["/login", "/register"];
    let headers = config.headers?config.headers:{}
    if (arr.indexOf(url) !== -1) {
      return axios.post(baseUrl + url, params, {
        ...config,
        headers: {
          ...headers
        }
      });
    } else {
      this.setToken(token);
      this.setXToKen(xtoken);
      return axios.post(baseUrl + url, params, {
        ...config,
        headers: {
          ...headers
        }
      });
    }
  },
  put(url, params = {}, config = {}) {
    let token = Storage.get(AUTH);
    let xtoken = Storage.get(XTOKEN);
    let headers = config.headers?config.headers:{}
    this.setToken(token);
    this.setXToKen(xtoken);
    return axios.put(baseUrl + url, params, {
      ...config,
      headers: {
        ...headers
      }
    });
  },
  setToken(token) {
    if(token){
      Storage.set(AUTH,token);
      axios.defaults.headers["Authorization"] = "Bearer " + token;
      this.setX_Token();
    }
  },
  setXToKen(xtoken) {
    Storage.set(XTOKEN,xtoken);
    axios.defaults.headers["xtoken"] = xtoken;
    this.setX_Token();
  },
  setX_Token() {
    axios.defaults.headers["x_token"] =
      Storage.get(X_TOKEN) ||
      Math.random()
        .toString(36)
        .substr(2);
  },
  async init() {
    await setX_Token();
  }
};
